<?php

namespace Popshouse\AdminBundle\Model;
use Symfony\Component\Translation\Loader\XliffFileLoader;

class Translation{

	
	const main = 'nl';
	const imgs = 'images';
	
	private $langs = array('nl','fr','en','de');
	
	//eg: 'housing'
	protected $domain;
	
	//eg: '$keys[1] = 'head.title'
	protected $keys = array();
	
	//eg: '$strings['nl']['head.title'] = 'Accommodatie'
	public $strings = array();
	
	protected $loader;
	
	public function __construct($domain){
		
		if(empty($domain))
			throw new \Exception("Geen domein opgegeven");
		$this->domain = $domain;
		$this->loader = new XliffFileLoader();
		//$this->load($domain);
	}

	public function getLangs(){
		return $this->langs;
	}
	
	public function addKey($key){
		$this->keys[] = $key;
		
		foreach($this->langs as $lang){
			$this->strings[$key][$lang] = '';
		}
	}
	
	public function removeKey($key){
		$this->keys = array_diff($this->keys, (array) $key);
		unset($this->strings[$key]);
	}
	
	public function set($key,$lang,$translation){
		
		if(!in_array($key,$this->keys)){
			$this->addKey($key);
		}
		
		if(!in_array($lang,$this->langs)){
			throw new \Exception("Deze taal wordt niet ondersteund.");
		}
		
		$this->strings[$key][$lang] = $translation;
		
	}
	
	private static function getTranslationDir(){
		
		return BUNDLES_PATH.'/Popshouse/SiteBundle/Resources/translations';
	}
	
	private function getFile($lang){
		return self::getTranslationDir() . '/' . $this->domain . '.' . $lang  . '.xliff';
	}
	
	public static function listAll($ignore = true){
		//die(self::getTranslationDir());
		if ($handle = opendir(self::getTranslationDir())){
			
			$ignorefiles = array();
			if($ignore)
				$ignorefiles[] = self::imgs;
				
			$files = array();
			while (false !== ($file = readdir($handle))) {
				if($file != '.' && $file != '..')
			   		$files[] = $file;
			}
			
			closedir($handle);
			
			$ffiles = array();
			
			foreach($files as $file){
				$file = explode('.',$file);
			
				if(sizeof($file) == 3 && $file[1] == self::main && !in_array($file[0],$ignorefiles))
					$ffiles[] = $file[0];
			}
		
			return $ffiles;
		}else{
		   	throw new \Exception("Kan vertaalbestanden niet vinden");
		}

	}
	
	public function load(){
		$this->keys = array();
		$this->strings = array();
		
		if(!in_array($this->domain,$this->listAll(false)))
			throw new \Exception("Dit domein bestaat niet");
		
		if(file_exists(self::getFile(self::main))){
			$this->loadBase($this->domain);
			
			foreach($this->langs as $lang){
				if($lang != self::main)
					$this->loadOne($lang);
			}
		}
	}

	
	private function loadBase(){
		$cat = $this->loader->load(self::getFile(self::main), self::main, $this->domain);
		$messages = $cat->all($this->domain);
		foreach($messages as $key => $string){
			$this->keys[] = $key;
			$this->set($key,self::main,$string);
		}
	}
	
	private function loadOne($lang){
		if(file_exists(self::getFile($lang))){
			$cat = $this->loader->load(self::getFile($lang), $lang, $this->domain);
			$messages = $cat->all($this->domain);
			
			foreach($this->keys as $key){
				if(array_key_exists($key,$messages))
					$this->set($key,$lang,$messages[$key]);
				else
					$this->set($key,$lang,'');
			}
		}
	}
	
	public function save(){
		foreach($this->langs as $lang){
			$this->saveOne($lang);
		}
	}
	
	private function saveOne($lang){
		$file = self::getFile($lang);
		

		$xmlstr = '<?xml version="1.0"?> 
		<xliff version="1.2" xmlns="urn:oasis:names:tc:xliff:document:1.2"> 
			<file source-language="'.$lang.'" datatype="plaintext" original="file.ext"> 
				<body> 
				</body>
			</file>
		</xliff>';
		
		
		$dom = new \DOMDocument();
		$dom->loadXML($xmlstr);
		$dom->formatOutput = true;
	
		$body = $dom->getElementsByTagName('body')->item(0);
		
		if(sizeof($this->keys)){
			$i=1;
			foreach($this->keys as $key){
				$trans_unit = $dom->createElement('trans-unit');
				$trans_unit = $body->appendChild($trans_unit);
				
				$id = $dom->createAttribute('id'); 
		    	$trans_unit->appendChild($id); 
		   	 	$id_text = $dom->createTextNode($i); 
	    		$id->appendChild($id_text);
	    		
	    		$trans_source = $dom->createElement('source',$key);
				$trans_source = $trans_unit->appendChild($trans_source);
				
				$val = array_key_exists($lang,$this->strings[$key]) ? $this->strings[$key][$lang] : '';
				
				$trans_target = $dom->createElement('target');
				$trans_target = $trans_unit->appendChild($trans_target);
				$trans_target->appendChild($dom->createTextNode($val));
				$i++;
			}
		}
		//die($dom->saveXML());
		$dom->save($file);
	}
	
	public function setDomain($domain){
		$this->domain = $domain;
		return $this;
	}
	
	public function getDomain(){
		return $this->domain;
	}
	
	public function getKeys(){
		return $this->keys;
	}
	
	public function delete(){
		foreach($this->langs as $lang){
			@unlink(self::getFile($lang));
		}
	}
}